package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.feign.client.WmUserFeignClient;
import com.heima.file.template.MinIOTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDto;
import com.heima.model.user.entity.ApUser;
import com.heima.model.wemedia.entity.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.model.user.entity.ApUserRealname;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.threadUtil.ThreadLocalUtil;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * APP实名认证信息表(ApUserRealname)表服务实现类
 *
 * @author makejava
 * @since 2023-06-26 17:57:01
 */
@Service("apUserRealnameService")
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Resource
    private MinIOTemplate minIOTemplate;

    @Resource
    private ApUserRealnameMapper apUserRealnameMapper;

    @Resource
    private WmUserFeignClient wmUserFeignClient;

    @Resource
    private ApUserMapper apUserMapper;

    /**
     * 用户提交实名认证信息
     * @param font_image
     * @param back_image
     * @param hold_image
     * @param live_image
     * @param name
     * @param idno
     * @return
     */
    @Override
    public ResponseResult submit(MultipartFile font_image, MultipartFile back_image, MultipartFile hold_image, MultipartFile live_image, String name, String idno) throws IOException {

        //姓名 证件好参数校验
        if(StringUtils.isEmpty(name)||StringUtils.isEmpty(idno)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //认证照片校验
        if(font_image.isEmpty()||back_image.isEmpty()||hold_image.isEmpty()||live_image.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"缺少证件照材料");
        }

        //上传照片到MinIO
        //1.上传正面照
        String fileName=font_image.getOriginalFilename();
        fileName= UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        String font_url = minIOTemplate.uploadImgFile("heima", fileName, font_image.getInputStream());

        //上传背面照
        fileName=back_image.getOriginalFilename();
        fileName= UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        String back_url = minIOTemplate.uploadImgFile("heima", fileName, back_image.getInputStream());

        //上传手持照
        fileName=hold_image.getOriginalFilename();
        fileName= UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        String hold_url = minIOTemplate.uploadImgFile("heima", fileName, hold_image.getInputStream());

        //上传活体照
        fileName=live_image.getOriginalFilename();
        fileName= UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        String live_url = minIOTemplate.uploadImgFile("heima", fileName, live_image.getInputStream());

        //封装数据
        ApUserRealname apUserRealname = ApUserRealname.builder()
                .userId(ThreadLocalUtil.get().getId().longValue())
                .name(name)
                .idno(idno)
                .fontImage(font_url)
                .backImage(back_url)
                .holdImage(hold_url)
                .liveImage(live_url)
                .status(1)
                .createdTime(new Date())
                .updatedTime(new Date())
                .build();

        //插入数据
        apUserRealnameMapper.insert(apUserRealname);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询实名认证列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult queryList(AuthDto dto) {

        //参数校验
        dto.checkParam();

        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();

        if(dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }

        Page<ApUserRealname> page = apUserRealnameMapper.selectPage(new Page<>(dto.getPage(), dto.getSize()), wrapper);

        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());

                return result;
    }

    @GlobalTransactional
    @Override
    public ResponseResult updateAuthStatus(AuthDto dto) {

        //参数校验
        if(dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //status==2 or status==9直接返回参数异常
        if(dto.getPage()==2||dto.getStatus()==9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUserRealname apUserRealname = apUserRealnameMapper.selectById(dto.getId());

        if(apUserRealname==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        apUserRealname.setStatus(dto.getStatus().intValue());
        if(StringUtils.isNotEmpty(dto.getMsg())){
            //msg非空  为审核失败 直接更新数据库
            apUserRealnameMapper.updateById(apUserRealname);
        }
        //调用自媒体服务创建自媒体账号
        if(dto.getStatus()==9){
            createWmUser(apUserRealname.getUserId());
        }

        return ResponseResult.okResult("操作成功");

    }

    /**
     * 远程调用自媒体服务保存自媒体信息
     * @param userId 用户Id
     *
     */
    private void createWmUser(Long userId) {
        //封装自媒体账户
        ApUser apUser = apUserMapper.selectById(userId);
        if(apUser==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setAvatar(apUser.getImage());
        wmUser.setNickname(apUser.getNicknme());
        wmUser.setStatus(1);
        wmUser.setType(1);
        wmUser.setApUserId(apUser.getId());
        ResponseResult responseResult = wmUserFeignClient.save(wmUser);

        if(responseResult.getCode()!=200){
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}

